package lvbu.wang.lvbuoperator.ui.paramset.presenter;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qing.library.utils.FileUtils;
import com.qing.library.utils.L;
import com.qing.library.utils.NetWorkUtil;
import com.qing.library.utils.StringUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;

import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.bean.BleMotorInfo;
import lvbu.wang.lvbuoperator.bean.FirmwareVersion;
import lvbu.wang.lvbuoperator.bean.JsonBikeMotor;
import lvbu.wang.lvbuoperator.bean.JsonMotor;
import lvbu.wang.lvbuoperator.bean.SendCommandResult;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.App;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.http.BleHttpHelp;
import lvbu.wang.lvbuoperator.http.IotHttpHelp;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.ui.paramset.ui.BleParamSetActivity;
import lvbu.wang.lvbuoperator.ui.paramset.ui.IBleParamSetView;
import lvbu.wang.lvbuoperator.ui.paramset.ui.IIotParamSetView;
import lvbu.wang.lvbuoperator.utils.CommandUtils;
import lvbu.wang.lvbuoperator.utils.CommonUtil;
import lvbu.wang.lvbuoperator.utils.FormatUtil;
import lvbu.wang.lvbuoperator.utils.StringHelper;

import static lvbu.wang.lvbuoperator.core.BaseActivity.sleep;

/**
 * Created by DaiQing.Zha on 2017/2/27 0027.
 */
public class BleParamSetPresenterCompl implements IBleParamSetPresenter {

    private Context mContext;
    private IBleParamSetView iBleParamSetView;
    private String[] mStatusCodeArr = {"01", "02", "03", "FF"};
    private String[] mStatusArr = {"不转状态", "微转状态", "强转状态", "正常状态"};
    private SimpleDateFormat df = new SimpleDateFormat("yyMMdd");//设置日期格式 example：2017-03-21 转换后：170321

    public BleParamSetPresenterCompl(IBleParamSetView iBleParamSetView) {
        this.iBleParamSetView = iBleParamSetView;
    }

    public BleParamSetPresenterCompl(IBleParamSetView iBleParamSetView, Context context) {
        this.iBleParamSetView = iBleParamSetView;
        mContext = context;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void clickConnectBluetooth(Context context) {
        int bluetoothStatus = BaseActivity.getMotorDefault_bluetooth_connect_state(context);
        if (!App.getInstance().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            iBleParamSetView.showToast(iBleParamSetView.TOAST_COMM_BLE_NOT_SUPPORT);
            return;
        }
        BluetoothManager mBluetoothManager = (BluetoothManager) App.getInstance().getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            iBleParamSetView.showToast(iBleParamSetView.TOAST_COMM_BLUETOOTH_NOT_OPEN);
        }
        if (bluetoothStatus == BluetoothLEService.Bluetooth_CONNECTING || bluetoothStatus == BluetoothLEService.Bluetooth_SCAN) { // 正在连接，提醒
            iBleParamSetView.showToast(iBleParamSetView.TOAST_COMM_BLE_CONNECTING);
            return;
        }
//        if (bluetoothStatus == BluetoothLEService.Bluetooth_CONNECTED) { // 已连接，断开连接
//            BluetoothLEService.disConnect();  // 断开车辆蓝牙
//            return;
//        }
        if (bluetoothStatus == BluetoothLEService.Bluetooth_UNCONNECT) { // 未连接，开始连接
            BluetoothLEService.connect(); // 连接车辆蓝牙
        }
    }

    private static final String TAG = "BleParamSetPresenterCompl";

    @Override
    public void clickGetDataByBluetooth() {
        ThreadPool.getInstance().addTask(() -> {
            String[] commandHeads = {"BA", "BB", "AC", "A5", "AB"   //硬件版本,固件版本,蓝牙地址,助力等级,轮胎周长
                    , "AE", "AF", "C3", "C4", "D2"   //车重,载重,电机状态,助力模式,上坡助力角度
                    , "D3", "D1", "D0"};    //上坡助力等级,电池功率,电池型号,电机系列（轮毂型号）
            StringBuffer sendCodeBuf = new StringBuffer();
            for (int i = 0; i < commandHeads.length; i++) {
                sendCodeBuf.append(commandHeads[i]);
            }
            String sendCode = sendCodeBuf.toString();
            sendCode = CommandUtils.FLAG_GET + sendCode;
            SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getInquireCommand(commandHeads));
            L.e("mainNewProtocolHH", "sendCode1 " + sendCodeBuf + " sendCodeMM1 = " + CommandUtils.getInquireCommand(commandHeads) + " scr1 = " + scr.toString());
            if (scr.isResult()) {
                try {
                    String answerResult = StringHelper.subString(scr.getAnswerContent(), 6, 8);
                    if ("01".equals(answerResult)) {
                        BleMotorInfo bleMotorInfo = App.getInstance().getBleMotorInfo();
                        HashMap map = CommandUtils.getInquireMap(scr.getAnswerContent());
                        Set set1 = map.keySet();
                        for (Object obj : set1) {
                            if (obj.equals("BA")) {  //硬件版本
                                bleMotorInfo.setHardwareVersion(String.valueOf(map.get(obj)));
                                L.e("mainNewProtocolHH", "hardWareVersion = " + String.valueOf(map.get(obj)));
                            }
                            if (obj.equals("BB")) {  //固件版本
                                bleMotorInfo.setFirmwareVersion(String.valueOf(map.get(obj)));
                            }
                            if (obj.equals("AC")) {  //蓝牙地址
                                bleMotorInfo.setBluetoothAddress(CommonUtil.convertBluetoothAddress(String.valueOf(map.get(obj))));
                            }
                            if (obj.equals("A5")) {  //助力等级
                                bleMotorInfo.setPowerLevel(Integer.parseInt(String.valueOf(map.get(obj)), 16));   //助力等级
                                L.e("mainNewProtocolHH", "powerLevel = " + Integer.valueOf(String.valueOf(map.get(obj)), 16));
                            }
                            if (obj.equals("AB")) {  //轮胎周长
                                bleMotorInfo.setCircumference(FormatUtil.str2Float(String.valueOf(map.get(obj)), 3));
                            }
                            if (obj.equals("AE")) {  //车重
                                bleMotorInfo.setBikeWeight((float) Integer.parseInt(String.valueOf(map.get(obj)), 16));
                            }
                            if (obj.equals("AF")) {  //载重
                                bleMotorInfo.setLoadWeight((float) Integer.parseInt(String.valueOf(map.get(obj)), 16));
                            }
                            if (obj.equals("C3")) {  //电机状态
                                bleMotorInfo.setStatusCode(String.valueOf(map.get(obj)));
                            }
                            if (obj.equals("C4")) {  //助力模式
                                bleMotorInfo.setAssistantMode(String.valueOf(map.get(obj)));
                            }
                            if (obj.equals("D2")) {  //上坡助力角度
                                bleMotorInfo.setUpHillAngle(FormatUtil.str2Float(String.valueOf(map.get(obj)), 1));
                            }
                            if (obj.equals("D3")) {  //上坡助力等级
                                bleMotorInfo.setUpHillPowerLevel(Integer.parseInt(String.valueOf(map.get(obj)), 16));
                            }
                            if (obj.equals("D1")) {  //电池功率
                                bleMotorInfo.setBatteryRate(Integer.parseInt(String.valueOf(map.get(obj)), 16));   //电池功率数
                            }
                            if (obj.equals("D0")) {  //电机系列
                                bleMotorInfo.setMotorSeries(StringUtil.string2Ascii(String.valueOf(map.get(obj))));
                            }
                        }
                        App.getInstance().setBikeMotor(bleMotorInfo);
                        iBleParamSetView.refreshUI_motorInfo();
                    } else {
                        //TODO:返回不是01
                        iBleParamSetView.showToast("获取数据失败!");
                    }
                } catch (Exception e) {
                    L.e("mainNewProtocolHH = ", "error error = " + e.toString());
                }
            } else {
                //TODO:应答失败
                iBleParamSetView.showToast("获取数据失败!");
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void clickBleSignalStrength(Context context) {
        if (BaseActivity.getMotorDefault_bluetooth_connect_state(context) != BluetoothLEService.Bluetooth_CONNECTED) {
            iBleParamSetView.showToast(IBleParamSetView.TOAST_COMM_BLE_IS_NOT_CONNECT);
        } else {
            try {
                BluetoothLEService.getmBluetoothGatt().readRemoteRssi();
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void clickGetVoltage(Context context) {
        iBleParamSetView.refreshUI_voltage("");
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {

                String commandHead = "C0";
                String sendCode = CommandUtils.FLAG_GET + commandHead;
                SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getInquireCommand(new String[]{commandHead}));
                if (scr.isResult()) {
                    answerProcessNewProtocol(scr.getAnswerContent());
                } else {
                    answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                }
            }
        });
    }

    @Override
    public void clickAdjustGyroAngle() {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {

                String commandHead = "BD";
                String sendCode = CommandUtils.FLAG_SET + commandHead;
                SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, ""));
                if (scr.isResult()) {
                    answerProcessNewProtocol(scr.getAnswerContent());
                } else {
                    answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                }
            }
        });
    }

    @Override
    public void clickRestart(Context context) {
        if (BluetoothLEService.Bluetooth_CONNECTED == BaseActivity.getMotorDefault_bluetooth_connect_state(context)) {
            byte[] bytes = new byte[]{0x33};
            if (BluetoothLEService.sendSwitchByBluetooth(bytes)) {
                iBleParamSetView.showToast(iBleParamSetView.TOAST_PARAM_SET_RESET_SUCCESS);
            } else {
                iBleParamSetView.showToast(iBleParamSetView.TOAST_PARAM_SET_RESET_FAIL);
            }
        } else {
            iBleParamSetView.showToast(iBleParamSetView.TOAST_COMM_BLE_IS_NOT_CONNECT);
        }
    }

    @Override
    public  void clickSysclose(Context context) {
        if (BluetoothLEService.Bluetooth_CONNECTED == BaseActivity.getMotorDefault_bluetooth_connect_state(context)) {
            byte[] bytes = new byte[]{0x32};
            if (BluetoothLEService.sendSwitchByBluetooth(bytes)) {
                iBleParamSetView.showToast(iBleParamSetView.TOAST_PARAM_SET_CLOSED_SUCCESS);
            } else {
                iBleParamSetView.showToast(iBleParamSetView.TOAST_PARAM_SET_RESET_FAIL);
            }
        } else {
            iBleParamSetView.showToast(iBleParamSetView.TOAST_COMM_BLE_IS_NOT_CONNECT);
        }
    }

    /**
     * 设置电机状态
     */
    @Override
    public void clickSetMotorStatus(final Context context) {
        final ArrayList<String> names = new ArrayList<String>();
        final ArrayList<String> values = new ArrayList<String>();
        for (int i = 0; i < 4; i++) {
            names.add(mStatusArr[i]);
            values.add(mStatusCodeArr[i]);
        }
        int index = -1;
        new AlertDialog.Builder(context).setTitle("设置电机状态").setSingleChoiceItems(names.toArray(new String[names.size()]), index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, final int which) {
                dialog.dismiss();
                iBleParamSetView.showProcess(iBleParamSetView.PROGRESS_CHANGE_STATUS_CHANGES_ING);
                ThreadPool.getInstance().addTask(new Runnable() {

                    @Override
                    public void run() {
                        // 第1步，改变电机状态
                        boolean result_motor = false;
                        Map<String, Object> queryStrings = new HashMap<>();
                        queryStrings.put("bluetoothAddress", BaseActivity.getBluetoothAddress(context));
                        queryStrings.put("statusCode", values.get(which));
                        String source = IotHttpHelp.getData(RouteConstant.API_MOTOR_BLE_SET_MOTOR_INFO_STATUS_CODE_UPDATE, queryStrings, true, context);
                        L.e("mainBike", "bluetoothAddress = " + BaseActivity.getBluetoothAddress(context) + " source = " + source);
                        if ("success".equals(source.replace("\"", ""))) {
                            result_motor = true;
                        } else {
                            result_motor = false;
                            iBleParamSetView.showToast(source);
                            iBleParamSetView.hideProcess();
                            return;
                        }

                        String commandHead = "C3";
                        String sendCode = CommandUtils.FLAG_SET + commandHead;
                        SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, values.get(which)));

                        Log.e("mainCommandDDD", "command = " + CommandUtils.getSetCommand(commandHead, values.get(which)));
                        if (scr.isResult()) {
                            L.e("mainNewProtocolHH", "scr = " + scr.getAnswerContent());
                            String answerResult = StringHelper.subString(scr.getAnswerContent(), 6, 8);
                            if (answerResult.equals("01")) {
                                result_motor = true;
                            } else {
                                result_motor = false;
                                iBleParamSetView.hideProcess();
                            }
                        } else {
                            result_motor = false;
                            iBleParamSetView.hideProcess();
                        }
                        if (result_motor == true) {
                            iBleParamSetView.hideProcess();
                            iBleParamSetView.refreshUI_motorStatus(mStatusArr[which]);
                        }
                    }
                });
            }
        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickSelectTypeName(final Context context, final String productId) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("productId", productId);
                final String source = BleHttpHelp.getData(RouteConstant.GET_LIST_JSON_MOTOR_BLUETOOTH_MOTOR_TYPE_DICT_BY_PRODUCT_ID, queryStrings, true, context);
                L.e("mainBLE---", "source = " + source);
                if (BleHttpHelp.checkSource(source) == false) {
                    iBleParamSetView.showToast(BleHttpHelp.source2Message(context, source));
                    return;
                }
                ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        final ArrayList<String> names = new ArrayList<String>();
                        final ArrayList<String> values = new ArrayList<String>();
                        List<JsonBikeMotor.MotorTypeDict> list = new Gson().fromJson(source, new TypeToken<List<JsonBikeMotor.MotorTypeDict>>() {
                        }.getType());
                        for (int i = 0; i < list.size(); i++) {
                            JsonBikeMotor.MotorTypeDict item = list.get(i);
                            names.add(item.getTypeName() + " (" + item.getBatteryQuantity() + "节" + item.getmAhOne() + "电池)");
                            values.add(item.getTypeName());
                        }
                        int index = -1;
                        new AlertDialog.Builder(context).setTitle("设置轮毂型号").setSingleChoiceItems(names.toArray(new String[names.size()]), index, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, final int which) {
                                iBleParamSetView.showProcess(IIotParamSetView.PROGRESS_TYPE_NAME);
                                Executors.newCachedThreadPool().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        Map<String, Object> queryStrings = new HashMap<>();
                                        queryStrings.put("bluetoothAddress", BaseActivity.getBluetoothAddress(context));
                                        queryStrings.put("typeName", values.get(which));
                                        String source = IotHttpHelp.getData(RouteConstant.API_MOTOR_BLE_SET_MOTOR_INFO_TYPE_NAME_UPDATE, queryStrings, true, context);
                                        if ("success".equals(source.replace("\"", ""))) {
                                            String ss = StringUtil.asciiStringToHex(values.get(which));
                                            L.e("mainQWERT", "HH = " + ss);
                                            String commandHead = "D0";
                                            String sendCode = CommandUtils.FLAG_SET + commandHead;
                                            SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, ss));
                                            iBleParamSetView.hideProcess();
                                            if (scr.isResult()) {
                                                answerProcessNewProtocol(scr.getAnswerContent());
                                            } else {
                                                answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                                            }
                                        } else {
                                            iBleParamSetView.showToast(source);
                                        }
                                    }
                                });
                                dialog.cancel();
                            }
                        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        }).show();
                    }
                });
            }
        });
    }

    /**
     * 设置轮胎周长
     *
     * @param context
     */
    @Override
    public void clickSelectCircumference(final Context context) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {

                Map<String, Object> queryStrings = new HashMap<String, Object>();
                final String source = BleHttpHelp.getData(RouteConstant.Get_List_JsonSaleProduct_ProductTyreSizeDict, queryStrings, true, context);

                Log.e("mainVBN", "source1 = " + source);
                if (BleHttpHelp.checkSource(source) == false) {
                    iBleParamSetView.showToast(BleHttpHelp.source2Message(context, source));
                    return;
                }
                ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        final ArrayList<String> names = new ArrayList<String>();
                        final ArrayList<Float> values = new ArrayList<Float>();
                        List<JsonMotor.MotorTyreDict> list = new Gson().fromJson(source, new TypeToken<List<JsonMotor.MotorTyreDict>>() {
                        }.getType());
                        for (int i = 0; i < list.size(); i++) {
                            JsonMotor.MotorTyreDict item = list.get(i);
                            names.add("(" + item.getName() + ") " + item.getCircumference());
                            values.add(item.getCircumference());
                        }
                        int index = -1;
                        new AlertDialog.Builder(context).setTitle("设置轮胎周长").setSingleChoiceItems(names.toArray(new String[names.size()]), index, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                iBleParamSetView.showProcess(IIotParamSetView.PROGRESS_CIRCUMFERENCE);
                                final float selected = values.get(which);// 当前选择的
                                Executors.newCachedThreadPool().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        Map<String, Object> queryStrings = new HashMap<>();
                                        queryStrings.put("bluetoothAddress", BaseActivity.getBluetoothAddress(context));
                                        queryStrings.put("circumference", selected);
                                        String source = IotHttpHelp.getData(RouteConstant.API_MOTOR_BLE_SET_MOTOR_INFO_CIRCUMFERENCE_UPDATE, queryStrings, true, context);
                                        if ("success".equals(source.replace("\"", ""))) {
                                            String wheelPerimeter = FormatUtil.getFrontCompleteStr(Integer.toHexString((int) (selected * 1000)), 4);
                                            String commandHead = "AB";
                                            String sendCode = CommandUtils.FLAG_SET + commandHead;
                                            SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, wheelPerimeter));
                                            iBleParamSetView.hideProcess();
                                            if (scr.isResult()) {
                                                answerProcessNewProtocol(scr.getAnswerContent());
                                            } else {
                                                answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                                            }
                                        } else {
                                            iBleParamSetView.showToast(source);
                                        }
                                    }
                                });

                                dialog.cancel();
                            }

                        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        }).show();
                    }
                });
            }
        });
    }

    @Override
    public void clickAdjustPowerLevel(final Context context) {
        String[] items = context.getResources().getStringArray(R.array.powerLevel);
        final int[] values = new int[100];
        for (int i = 0; i < 100; i++) {
            values[i] = i;
        }
        int index = -1;
        for (int i = 0; i < values.length; i++) {
            if (App.getInstance().getBleMotorInfo().getPowerLevel() == values[i]) {
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("修改助力等级").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                iBleParamSetView.showProcess(IBleParamSetView.PROGRESS_ADJUST_POWER_LEVEL_ING);
                final int selected = values[which];// 当前选择的
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {

                        String commandHead = "A5";
                        String sendCode = CommandUtils.FLAG_SET + commandHead;
                        SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, FormatUtil.intToHex(selected)));
                        iBleParamSetView.hideProcess();
                        if (scr.isResult()) {
                            answerProcessNewProtocol(scr.getAnswerContent());
                        } else {
                            answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                        }
                    }
                });
                dialog.cancel();
            }
        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickOverSpeedAlarm(Context context) {
        final String[] items = context.getResources().getStringArray(R.array.overSpeed);
        final int[] overSpeeds = new int[42];
        overSpeeds[0] = 0;
        for (int i = 1; i < 42; i++) {
            overSpeeds[i] = i + 9;
        }
        int index = 0;
        for (int i = 0; i < overSpeeds.length; i++) {
            if (App.getInstance().getBleMotorInfo().getSpeedLimitValue() == overSpeeds[i]) {
                index = i;
                break;
            }
        }
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            arrayList.add(items[i]);
        }
        new AlertDialog.Builder(context).setTitle("修改超速报警").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, final int which) {
                iBleParamSetView.showProcess(IBleParamSetView.PROGRESS_ADJUST_POWER_LEVEL_ING);
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {

                        String commandHead = "A6";
                        String sendCode = CommandUtils.FLAG_SET + commandHead;
                        float overSpeedSelected = overSpeeds[which];   // 当前选择的
                        SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, FormatUtil.intToHex((int) overSpeedSelected)));
                        iBleParamSetView.hideProcess();
                        if (scr.isResult()) {
                            answerProcessNewProtocol(scr.getAnswerContent());
                        } else {
                            answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                        }
                    }
                });
                dialog.cancel();
            }
        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickBikeWeight(final Context context) {
        final String[] items = context.getResources().getStringArray(R.array.bikeWeight);
        final int[] values = new int[41];
        values[0] = 0;
        for (int i = 0; i < 41; i++) {
            values[i] = i + 10;
        }
        int index = -1;
        for (int i = 0; i < values.length; i++) {
            if (App.getInstance().getBleMotorInfo().getBikeWeight() == values[i]) {
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("修改车重").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, final int which) {
                iBleParamSetView.showProcess(iBleParamSetView.PROGRESS_ADJUST_BIKE_WEIGHT);
                final float selected = values[which];// 当前选择的
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        final float bikeWeightSelected = values[which];// 当前选择的
                        Map<String, Object> queryStrings = new HashMap<>();
                        queryStrings.put("bluetoothAddress", BaseActivity.getBluetoothAddress(context));
                        queryStrings.put("bikeWeight", bikeWeightSelected);
                        String source = IotHttpHelp.getData(RouteConstant.API_MOTOR_BLE_SET_MOTOR_INFO_BIKE_WEIGHT_UPDATE, queryStrings, true, context);
                        if ("success".equals(source.replace("\"", ""))) {
                            String commandHead = "AE";
                            String sendCode = CommandUtils.FLAG_SET + commandHead;
                            SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, FormatUtil.intToHex((int) bikeWeightSelected)));
                            iBleParamSetView.hideProcess();
                            if (scr.isResult()) {
                                answerProcessNewProtocol(scr.getAnswerContent());
                            } else {
                                answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                            }
                        } else {
                            iBleParamSetView.showToast(source);
                        }

                    }
                });
                dialog.cancel();
            }
        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickLoadWeight(final Context context) {
        final String[] items = context.getResources().getStringArray(R.array.loadWeight);
        final int[] loadWeightArr = new int[171];
        loadWeightArr[0] = 0;
        for (int i = 0; i < 171; i++) {
            loadWeightArr[i] = i + 30;
        }
        int index = -1;
        for (int i = 0; i < loadWeightArr.length; i++) {
            if (App.getInstance().getBleMotorInfo().getLoadWeight() == loadWeightArr[i]) {
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("修改载重").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, final int which) {
                iBleParamSetView.showProcess(iBleParamSetView.PROGRESS_ADJUST_LOAD_WEIGHT);
                final float selected = loadWeightArr[which];// 当前选择的
                ThreadPool.getInstance().addTask(new Runnable() {

                    @Override
                    public void run() {

                        Map<String, Object> queryStrings = new HashMap<>();
                        queryStrings.put("bluetoothAddress", BaseActivity.getBluetoothAddress(context));
                        queryStrings.put("loadWeight", selected);
                        String source = IotHttpHelp.getData(RouteConstant.API_MOTOR_BLE_SET_MOTOR_INFO_LOAD_WEIGHT_UPDATE, queryStrings, true, context);
                        if ("success".equals(source.replace("\"", ""))) {
                            float loadWeightSelected = loadWeightArr[which];// 当前选择的
                            String commandHead = "AF";
                            String sendCode = CommandUtils.FLAG_SET + commandHead;
                            SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, FormatUtil.intToHex((int) loadWeightSelected)));
                            iBleParamSetView.hideProcess();
                            if (scr.isResult()) {
                                answerProcessNewProtocol(scr.getAnswerContent());
                            } else {
                                answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                            }
                        } else {
                            iBleParamSetView.showToast(source);
                        }
                    }
                });
                dialog.cancel();
            }

        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    /**
     * 修改名称
     *
     * @param context
     */
    @SuppressLint("LongLogTag")
    @Override
    public void clickModifyName(final Context context) {
        final String[] items = context.getResources().getStringArray(R.array.BikeName);
        final String[] bikeName = new String[2];
        bikeName[0] = items[0];
        bikeName[1] = items[1];

        int index = 0;
        for (int i = 0; i < bikeName.length;i++){
            Log.e(TAG, "clickModifyName: " + bikeName[i] + App.getInstance().getMotorInfo().getMotorName(),null);
            if (App.getInstance().getBleMotorInfo().getMotorName().equals(bikeName[i])){
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("修改名称").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @SuppressLint("LongLogTag")
            @Override
            public void onClick(DialogInterface dialog, final int which) {
                iBleParamSetView.showProcess(iBleParamSetView.PROGRESS_ADJUST_LOAD_WEIGHT);
                final String selected = bikeName[which];// 当前选择的
                Log.e(TAG, "onClick: " + selected, null);
                ThreadPool.getInstance().addTask(new Runnable() {

                    @SuppressLint("LongLogTag")
                    @Override
                    public void run() {
                        if (selected != null && !"".equals(selected)) {
                            //检查蓝牙是否连接
                            if (BluetoothLEService.getBluetoothState() != BluetoothLEService.Bluetooth_CONNECTED) {
                                iBleParamSetView.showToast(IBleParamSetView.TOAST_COMM_BLE_IS_NOT_CONNECT);
                                return;
                            }
                            BluetoothLEService.sendChangeMotorName_bluetooth("[" + selected + "]");
                            long time = System.currentTimeMillis();
                            Log.e(TAG, "run: " + BluetoothLEService.BLE_NAME, null);
                            //53554343455353
                            while (true) {
                                if (BluetoothLEService.BLE_NAME.equals("53554343455353")) {  //收到success表示改名成功
                                    Log.e(TAG, "run: 修改名称成功" + selected, null);
                                    BluetoothLEService.BLE_NAME = "";
                                    App.getInstance().getMotorInfo().setMotorName(selected);
                                    App.getInstance().getBleMotorInfo().setMotorName(selected);
                                    iBleParamSetView.refreshUI_bikeName(selected);
                                    iBleParamSetView.showToast("修改名字成功");
                                    iBleParamSetView.hideProcess();
                                    break;
                                } else {
                                    if (System.currentTimeMillis() - time > 3000) {
                                        iBleParamSetView.showToast("修改名字失败");
                                        iBleParamSetView.hideProcess();
                                        break;
                                    }
                                }
                                sleep(100);

                            }
                        }
                    }
                });
                dialog.cancel();
            }

        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickBatteryPowerAndBatteryModel(final Context context, final String productId) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("productId", productId);
                final String source = BleHttpHelp.getData(RouteConstant.GET_LIST_JSON_MOTOR_BLUETOOTH_MOTOR_TYPE_DICT_BY_PRODUCT_ID, queryStrings, true, context);
                L.e("mainBLE---", "source = " + source);
                if (BleHttpHelp.checkSource(source) == false) {
                    iBleParamSetView.showToast(BleHttpHelp.source2Message(context, source));
                    return;
                }
                ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        final ArrayList<String> names = new ArrayList<String>();
                        final ArrayList<String> values = new ArrayList<String>();
                        final List<JsonBikeMotor.MotorTypeDict> list = new Gson().fromJson(source, new TypeToken<List<JsonBikeMotor.MotorTypeDict>>() {
                        }.getType());
                        for (int i = 0; i < list.size(); i++) {
                            JsonBikeMotor.MotorTypeDict item = list.get(i);
                            names.add("功率:" + item.getWhTotal() + "/型号:" + item.getBatteryBrandModel());
                            values.add(item.getTypeName());
                        }
                        int index = -1;
                        new AlertDialog.Builder(context).setTitle("设置电池功率和型号").setSingleChoiceItems(names.toArray(new String[names.size()]), index, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, final int which) {
                                Executors.newCachedThreadPool().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        int whTotal = (int) Float.parseFloat(list.get(which).getWhTotal());
                                        String commandHeadBatteryRate = "D1";
                                        String sendCodeBatteryRate = CommandUtils.FLAG_SET + commandHeadBatteryRate;
                                        SendCommandResult scrBatteryRate = BluetoothLEService.sendCommandByBluetooth(sendCodeBatteryRate,
                                                CommandUtils.getSetCommand(commandHeadBatteryRate, FormatUtil.getFrontCompleteStr(FormatUtil.intToHex(whTotal), 4)));
                                        Log.e("mainNewProtocolHH", "HD1 = " + CommandUtils.getSetCommand(commandHeadBatteryRate, FormatUtil.getFrontCompleteStr(FormatUtil.intToHex(whTotal), 4)) + " whTotal = " + FormatUtil.intToHex(whTotal));

                                        if (scrBatteryRate.isResult()) {

                                            String valueBatteryRate = StringHelper.subString(scrBatteryRate.getAnswerContent(), 10, scrBatteryRate.getAnswerContent().length() - 4);
                                            int rate = Integer.parseInt(valueBatteryRate, 16);
                                            iBleParamSetView.refreshUI_batteryPowerAndMode(rate + "");
                                        } else {
                                            iBleParamSetView.showToast("设置失败，请重新设置！");
                                        }
                                    }
                                });
                                dialog.cancel();
                            }
                        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        }).show();
                    }
                });
            }
        });
    }

    @Override
    public void clickSetMadeDate() {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String commandHead = "D5";
                String sendCode = CommandUtils.FLAG_SET + commandHead;
                SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, FormatUtil.getTimeD5()));
                Log.e("mainHHHVVV", "SCR0BD5 = " + scr.toString() + "time = " + CommandUtils.getSetCommand(commandHead, FormatUtil.getTimeD5()));
                if (scr.isResult()) {
                    answerProcessNewProtocol(scr.getAnswerContent());
                } else {
                    answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                }
            }
        });
    }

    @Override
    public void clickGetMadeData() {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String commandHead = "D5";
                String sendCode = CommandUtils.FLAG_GET + commandHead;
                SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getInquireCommand(new String[]{commandHead}));
                Log.e("mainHHHVVV", "SCR0CD5GET = " + scr.toString());
                if (scr.isResult()) {
                    answerProcessNewProtocol(scr.getAnswerContent());
                } else {
                    answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                }
            }
        });
    }

    @Override
    public void clickUpdateFirmware(final Context context, final FirmwareVersion firmwareVersion) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                downloadFirmware(context, firmwareVersion);
            }
        });
    }


    /**
     * 下载固件
     *
     * @param firmwareVersion
     */
    private void downloadFirmware(Context context, FirmwareVersion firmwareVersion) {
        File sdCardDir = new File(FileUtils.getSDCacheDir(context));
        String url = firmwareVersion.getDownloadPath();
        BleParamSetActivity.fileName = url.substring(url.lastIndexOf("/") + 1);
        BleParamSetActivity.fileName = "simpleBike_" + BleParamSetActivity.fileName;
        File sdFile = new File(sdCardDir, BleParamSetActivity.fileName);
        if (sdFile.exists()) {
            checkIsCanUpdate(context);
        } else {
            try {
                URL myURL = new URL(url);
                URLConnection conn = myURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                BleParamSetActivity.fileSize = conn.getContentLength();//根据响应获取文件大小
                if (BleParamSetActivity.fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
                if (is == null) throw new RuntimeException("stream is null");
                if (sdCardDir.exists()) {
                    sdCardDir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(sdCardDir + "/" + BleParamSetActivity.fileName);
                //把数据存入路径+文件名
                byte buf[] = new byte[1024];
                BleParamSetActivity.downLoadFileSize = 0;
                iBleParamSetView.refreshUI_downLoadProgress(BleParamSetActivity.FILE_MAX_SIZE);
                do {
                    //循环读取
                    int numread = is.read(buf);
                    if (numread == -1) {
                        break;
                    }
                    fos.write(buf, 0, numread);
                    BleParamSetActivity.downLoadFileSize += numread;
                    try {
                        Thread.sleep(15);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    iBleParamSetView.refreshUI_downLoadProgress(BleParamSetActivity.UPDATE_PROGRESS);//更新进度条
                } while (true);
                iBleParamSetView.refreshUI_downLoadProgress(BleParamSetActivity.DOWNLOAD_COMPLETE);//通知下载完成
            } catch (MalformedURLException e) {
                e.printStackTrace();
                iBleParamSetView.showToast(context.getString(R.string.toast_comm_malformedError));
                iBleParamSetView.refreshUI_dismissDownload();
                sdFile.delete();
            } catch (IOException e) {
                iBleParamSetView.showToast(context.getString(R.string.xml_paramSet_dialogDownloadFail));
                iBleParamSetView.refreshUI_dismissDownload();
                e.printStackTrace();
                sdFile.delete();
            }
        }
    }

    /**
     * 检查是否可以进行固件升级
     */
    @Override
    public void checkIsCanUpdate(final Context context) {
        if (BaseActivity.getMotorDefault_bluetooth_connect_state(context) != BluetoothLEService.Bluetooth_CONNECTED) {
            iBleParamSetView.showToast(context.getString(R.string.comm_bleServer_bleNotConnect));
            return;
        }
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String commandHead = "B5";
                String sendCode = CommandUtils.FLAG_SET + commandHead;
                SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getSetCommand(commandHead, ""));
                L.e("mainHHH", "SCR = " + scr.toString());
                if (scr.isResult()) {
                    answerProcessNewProtocol(scr.getAnswerContent());
                } else {
                    answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                }
            }
        });
    }

    @Override
    public void checkIsHaveNewFirmware(final Context context) {
        if (!NetWorkUtil.isNetworkAvailable((Activity) context) || BaseActivity.getMotorDefault_bluetooth_connect_state(context) != BluetoothLEService.Bluetooth_CONNECTED)
            return;
        ThreadPool.getInstance().addTask(new Runnable() {

            @Override
            public void run() {
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("hardwareVersion", App.getInstance().getBleMotorInfo().getHardwareVersion());
                queryStrings.put("firmwareVersion", App.getInstance().getBleMotorInfo().getFirmwareVersion());
                final String source = IotHttpHelp.getData(RouteConstant.API_MOTOR_BLE_GET_JSON_MOTOR_CHEAP_FIRMWARE_INFO_NEW, queryStrings, true, context);
                Log.e("mainVBNJKLOP", "source = " + source);
                try {
                    FirmwareVersion firmwareVersion = new Gson().fromJson(source, FirmwareVersion.class);
                    iBleParamSetView.refreshUI_checkFirmware(firmwareVersion);
                } catch (Exception e) {
                }
            }
        });
    }

    /**
     * 新蓝牙协议应答正确处理
     *
     * @param answerContent
     */
    private void answerProcessNewProtocol(String answerContent) {
        String flag = StringHelper.subString(answerContent, 4, 6);
        String answerResult = StringHelper.subString(answerContent, 6, 8);
        if (CommandUtils.FLAG_SET.equals(flag)) {
            String key = flag + StringHelper.subString(answerContent, 8, 10);
            String value = StringHelper.subString(answerContent, 10, answerContent.length() - 4);
            answerProcessNewProtocol(key, value, answerResult);
        } else if (CommandUtils.FLAG_GET.equals(flag)) {
            HashMap map = CommandUtils.getInquireMap(answerContent);
            Set set1 = map.keySet();
            for (Object obj : set1) {
                String key = CommandUtils.FLAG_GET + String.valueOf(obj.toString());
                String value = String.valueOf(map.get(obj));
                answerProcessNewProtocol(key, value, answerResult);
            }
        }
    }

    /**
     * 新蓝牙协议应答正确处理（单个命令）
     *
     * @param key
     * @param value
     */
    private void answerProcessNewProtocol(String key, String value, String answerResult) {
        switch (key) {
            case "0BA5":  //助力等级
                L.e("mainNewProtocol", "key = " + key + " value = " + value + " answerResult = " + answerResult);
                if ("01".equals(answerResult)) { //应答成功
                    String flag = StringHelper.subString(value, 0, 1);
                    int powerLevel;
                    if ("0".equals(flag)) {
                        powerLevel = Integer.parseInt(value, 16);
                        App.getInstance().getBleMotorInfo().setPowerLevel(powerLevel);
                        L.e("mainProgress_Q", "flag1 = " + powerLevel);
                    } else {
                        powerLevel = Integer.parseInt(value, 16);
                        App.getInstance().getBleMotorInfo().setPowerLevel(powerLevel);
                        L.e("mainProgress_Q", "flag2 = " + powerLevel);
                    }
                    iBleParamSetView.refreshUI_powerLevel(String.valueOf(powerLevel));
                } else {  //应答失败
                    iBleParamSetView.showToast("调节助力等级失败");
                }
                break;
            case "0BA6":
                if ("01".equals(answerResult)) {
                    App.getInstance().getBleMotorInfo().setSpeedLimitValue(Integer.parseInt(value, 16));
                    int overSpeedValue = Integer.parseInt(value, 16);
                    L.e("mainHH", "FF = " + overSpeedValue);
                    if (overSpeedValue == 0) {
                        iBleParamSetView.refreshUI_overSpeed("不报警");
                    } else {
                        iBleParamSetView.refreshUI_overSpeed(String.valueOf(overSpeedValue));
                    }
                } else {
                    iBleParamSetView.showToast("调节超速报警失败");
                }
                break;
            case "0BAE":  //车重
                if ("01".equals(answerResult)) {
                    App.getInstance().getBleMotorInfo().setBikeWeight((float) Integer.parseInt(value, 16));
                    iBleParamSetView.refreshUI_bikeWeight(String.valueOf(Integer.parseInt(value, 16)));
                } else {
                    iBleParamSetView.showToast("修改车重失败");
                }
                break;
            case "0BAF":  //载重
                if ("01".equals(answerResult)) {
                    App.getInstance().getBleMotorInfo().setLoadWeight((float) Integer.parseInt(value, 16));
                    iBleParamSetView.refreshUI_loadWeight(String.valueOf(Integer.parseInt(value, 16)));
                } else {
                    iBleParamSetView.showToast("修改载重失败");
                }
                break;
            case "0BAB":
                String strPerimeter = String.valueOf(FormatUtil.str2Float(value, 3));
                App.getInstance().getBleMotorInfo().setCircumference(FormatUtil.str2Float(value, 3));
                iBleParamSetView.refreshUI_circumference(strPerimeter);
                break;
            case "0CC0":
                if ("01".equals(answerResult)) {
                    final Float voltage = FormatUtil.str2Float(value, 1);
                    iBleParamSetView.refreshUI_voltage(String.valueOf(voltage));
                }
                break;
            case "0BD0":
                if ("01".equals(answerResult)) { //07a8014258333043

                    BleMotorInfo motorInfo = App.getInstance().getBleMotorInfo();
                    motorInfo.setMotorSeries(StringUtil.string2Ascii(value));
                    App.getInstance().setBikeMotor(motorInfo);
                    iBleParamSetView.refreshUI_typeName(motorInfo.getMotorSeries());
                } else if ("02".equals(answerResult)) {
                    iBleParamSetView.showToast("设置轮毂型号失败!");
                }
                break;
            case "0BD1":
                if ("01".equals(answerResult)) { //07a8014258333043

                    BleMotorInfo motorInfo = App.getInstance().getBleMotorInfo();
                    motorInfo.setMotorSeries(StringUtil.string2Ascii(value));
                    App.getInstance().setBikeMotor(motorInfo);
                    iBleParamSetView.refreshUI_typeName(motorInfo.getMotorSeries());
                } else if ("02".equals(answerResult)) {
                    iBleParamSetView.showToast("设置电池功率失败!");
                }
                break;
            case "0BD5":
                if ("01".equals(answerResult)) {
                    iBleParamSetView.showToast("设置时间成功!");
                    Log.e("mainHHHVVV", "value = " + value);
                    iBleParamSetView.refreshUI_madeDate(FormatUtil.parseTimeHexToInt(value));
                } else if ("02".equals(answerResult)) {
                    iBleParamSetView.showToast("设置时间失败!");
                } else if ("03".equals(answerResult)) {
                    iBleParamSetView.showToast("时间无效!");
                }
                break;
            case "0BB5":
                if ("01".equals(answerResult)) {
                    if ("01".equals(value)) { //升级条件正常
                        Log.e("mainNewProtocol", "升级条件正常");
                    } else if ("02".equals(value)) {   //速度非零
                        iBleParamSetView.showToast("车辆处于非静止状态，请保持车辆静止");
                    } else if ("03".equals(value)) {   //电压不足
                        iBleParamSetView.showToast("电池电压过低，请保持电压在30伏以上");
                    }
                } else if ("02".equals(answerResult)) {

                }
                break;
            case "0CD5":
                Log.e("mainHHHVVV", "getTime = " + value);
                if ("01".equals(answerResult)) {
                    iBleParamSetView.refreshUI_getMadeDate(FormatUtil.parseTimeHexToInt(value));
                } else {
//                    iBleParamSetView.showToast("获取时间失败!");
                }
                break;
        }
    }

    /**
     * 新蓝牙协议应答错误处理
     *
     * @param key
     * @param errorMessage
     */
    private void answerErrorNewProtocol(String key, String errorMessage) {
        switch (key) {
            case "0BA5":
            case "0BAB":
            case "0BAE":
            case "0BAF":
            case "0BD0":
            case "0CC0":
            case "B8":
                iBleParamSetView.showToast(errorMessage);
                break;
            case "0CD5":
//                iBleParamSetView.showToast("获取出厂日期失败");
                break;
        }
    }

}
